/**
 * Notes: 接口封装Promise逻辑
 * Ver : CCMiniCloud Framework 2.0.1 ALL RIGHTS RESERVED BY cclinux0730 (wechat)
 * Date: 2022-05-22 07:48:00 
 */

const helper = require('../../helper/helper.js');
// const BASE_USL = 'http://ccc.bahea.com/byyyccctest';
const BASE_USL = 'http://192.168.5.62:8090/byyyccc_war_exploded';

class RequestBiz {

	static async request (url, args) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: BASE_USL + url,
        method: 'POST',
        data: args,
        success: resolve,
        fail: reject
      })
    })
  }

	static async requestNotJson (url, args) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: BASE_USL + url,
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded',
        },
        data: args,
        success: resolve,
        fail: reject
      })
    })
  }

	static async uploadFile (url, file, param) {
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url: BASE_USL + url,
        filePath: file,
        formData: param,
        name: 'file',
        success: resolve,
        fail: reject
      });
    })
  }

  static async uploadFormsTempPics(forms, url, param) {
    for (let k = 0; k < forms.length; k++) {
      if (forms[k].type == 'image') {
        for (let i = 0; i < forms[k].val.length; i++) {
          if (forms[k].val[i].includes('http://tmp')) {
            let ret = await this.uploadFile(url, forms[k].val[i], param);
            forms[k].val[i] = JSON.parse(ret.data).data;
          }
        }
      }
    }
  }

	static async dataList (that, listName, url, args, fields) {
    let data = {};
    if (!helper.isDefined(that.data[listName]) || !that.data[listName]) {
      data[listName] = {
        page: 1,
        size: that.data.limitPageSize,
        list: [],
        count: 0,
        total: 0,
        oldTotal: 0
      };
      that.setData(data);
    }
    else {
      data[listName] = that.data[listName]
    }

    let params = {
      'page': data[listName].page,
      'row': data[listName].size,
      'page.pn': data[listName].page,
      'page.size': data[listName].size,
      'queryFields': fields
    }

    // 查询参数
    for (var key in args) {
      params[key] = args[key];
      params['query.' + key + '||like'] = args[key];
    }

    await this.requestNotJson(url, params).then(res => {
      let retData = res.data;
      let tList = that.data[listName].list;
      if (retData.page == 1) {
        tList = retData.results;
      } else {
          tList = tList.concat(retData.results);
      }
      data[listName].list = tList;
      data[listName].page = retData.page;
      data[listName].total = retData.total;
      that.setData(data);
    });

  }
	 
}

module.exports = RequestBiz;